package com.nommon.menu;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.MotionEvent;

import com.nommon.tool.Vector2D;

public class Joystick {

	private static final int RADIUS = 80;
	private static final int INNER_RADIUS = 25;
	/**accept touch x% out of maincircle*/
	private static final float OVERTOUCH = 1.3f;

	private Point screenPosition;
	private Vector2D joystickState;
	
	/**
	 * negatives = from bottom right
	 * @param x
	 * @param y
	 */
	public Joystick(int x, int y) {
		screenPosition = new Point(x, y);
		joystickState = new Vector2D(0, 0);
	}

	public void draw(Canvas canvas) {
		if (screenPosition.y < 0){
			screenPosition.y += canvas.getHeight()-2*RADIUS;
		}
		if (screenPosition.x < 0){
			screenPosition.x += canvas.getWidth()-2*RADIUS;
		}
		Paint paint = new Paint();
		paint.setARGB(210, 64, 64, 64);
		canvas.drawCircle(screenPosition.x+RADIUS, screenPosition.y+RADIUS, RADIUS, paint);
		paint.setARGB(230, 128, 128, 128);
		canvas.drawCircle(
				screenPosition.x+RADIUS+(joystickState.x()*(RADIUS-INNER_RADIUS)), 
				screenPosition.y+RADIUS+(joystickState.y()*(RADIUS-INNER_RADIUS)), 
				INNER_RADIUS, paint);
		
	}
	
	public Vector2D getJoystickState(){
		return joystickState.clone();
	}

	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() != MotionEvent.ACTION_UP){
			for (int i=0; i<event.getPointerCount(); i++){
				Vector2D v = new Vector2D(event.getX(i) - screenPosition.x - RADIUS, 
						event.getY(i) - screenPosition.y-RADIUS);
				float length = v.getLength();
				if (length < RADIUS * OVERTOUCH){
					if (length < RADIUS){
						v.scale(1f/RADIUS);
					}else{
						v.normalize();
					}
					joystickState = v;
//					android.util.Log.e("", v.x()+" | "+v.y());
					return true;
				}
			}
		}
		joystickState = new Vector2D(0, 0);
		return false;
	}

}
